#include <cstdlib>
#include <cstdio>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include <vector>

#define BUFFER_SIZE 1024
#define PORT 8127
#define MSG "awk"


int main(int argc, char * argv[])
{
  int mainSocket, clientLen, currSocket;
  struct sockaddr_in serverStruct, clientStruct;

  unsigned short port;

  char buffer[BUFFER_SIZE];

  if (argc > 1)
    port = (unsigned short)atoi(argv[1]);
  else {
    printf("Using default port value: %d\n", PORT);
    port = PORT; 
  }
  
  
  mainSocket = socket(PF_INET, SOCK_STREAM, 0);

  serverStruct.sin_family = PF_INET;
  serverStruct.sin_addr.s_addr = INADDR_ANY;
  serverStruct.sin_port = htons(port);
  
  
  if (bind(mainSocket, (struct sockaddr *)&serverStruct, (int)sizeof(serverStruct)) < 0) {
    perror("bind()");
    exit(1);
  }
  
  clientLen = sizeof(clientStruct);
  
  listen(mainSocket, 5);
  
  while (1) {
    
    int pid;
    
    printf("Waiting for accept()\n");
    currSocket = accept(mainSocket, (struct sockaddr *)&clientStruct, (socklen_t*)&clientLen);
    
    pid = fork();
    if (pid==0) {
      int n = (int)recv(currSocket, buffer, BUFFER_SIZE - 1, 0);
      if (n<1)
	perror("recv()");
      else {
	buffer[n] = '\0';
	printf("%s (%d): %s\n", inet_ntoa((struct in_addr)clientStruct.sin_addr), 
	       (int)getpid(), buffer);
      }
      
      n = (int)send(currSocket, MSG, strlen(MSG), 0);
      
      if (n<(int)strlen(MSG))
	perror("send()");
      
      close(currSocket);
      exit(0);
    }
    close(currSocket);
  }

  return 0;
}
